package com.goodving.guli.bt.weight;

import android.content.Context;
import android.text.TextUtils;

import com.activeandroid.ActiveAndroid;
import com.activeandroid.query.Delete;
import com.activeandroid.query.From;
import com.activeandroid.query.Select;
import com.goodving.guli.bt.model.Friend;
import com.goodving.guli.bt.model.PersonInfo;
import com.goodving.guli.bt.model.WeightInfo;
import com.goodving.guli.bt.model.WeightInfoManager;
import com.goodving.guli.bt.profile.scale.GuliLog;
import com.goodving.guli.bt.utils.aE;
import com.goodving.guli.model.Keeper;
import com.goodving.guli.model.SyncResult;
import com.goodving.guli.server.ClientDataConstants;
import com.goodving.guli.server.C1980O;
import com.goodving.guli.server.WebAPI;
import com.goodving.guli.server.WebResponse;
import com.goodving.guli.utility.Constants;
import com.goodving.guli.view.C3657a;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import cn.com.smartdevices.bracelet.config.C0886a;
import cz.msebera.android.httpclient.Header;

/**
 * Created by john on 2015/12/1.
 */
public class UserInfoManager { // C1975J
    private static final String TAG = "UserInfoManager";
    private static UserInfoManager userInfoManager;

    private UserInfoManager() {
    }

    public static UserInfoManager getInstance() { // m15565a
        if (userInfoManager == null) {
            userInfoManager = new UserInfoManager();
        }
        return userInfoManager;
    }

    private String m15567a(String str, UserInfo userInfo) {
        String str2 = null;
        try {
            JSONObject jSONObject = new JSONObject(str).getJSONObject("data");
            if (jSONObject.getInt("fuid") == userInfo.uid) {
                str2 = jSONObject.getString("avatar");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str2;
    }

    private List<UserInfo> getUserListFromWebResponse(String str) { // m15570b
        try {
            JSONObject jSONObject = new JSONObject(str).getJSONObject("data");
            List<UserInfo> arrayList = new ArrayList(jSONObject.getInt("total"));
            JSONArray jSONArray = jSONObject.getJSONArray("list");
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject jSONObject2 = jSONArray.getJSONObject(i);
                UserInfo userInfo = new UserInfo();
                userInfo.uid = jSONObject2.getInt("fuid");
                userInfo.height = jSONObject2.getInt(ClientDataConstants.PARAM_BIND_HEIGHT);
                userInfo.gender = jSONObject2.optInt(ClientDataConstants.PARAM_BIND_GENDER);
                userInfo.birthday = jSONObject2.optString("birthday");
                userInfo.name = jSONObject2.getString("nickname");
                userInfo.avatarUrl = jSONObject2.optString("avatar");
                userInfo.weight = Float.valueOf(jSONObject2.optString(Friend.f7788d, Constants.VIA_RESULT_SUCCESS)).floatValue();
                userInfo.targetWeight = Float.valueOf(jSONObject2.optString("targetweight", Constants.VIA_RESULT_SUCCESS)).floatValue();
                if (userInfo.uid == 0) {
                    GuliLog.m12370d(TAG, "Sync UserInfo Id Unknown : " + userInfo);
                } else if (userInfo.uid == -1) {
                    GuliLog.m12370d(TAG, "Sync UserInfo Id Self : " + userInfo);
                } else {
                    arrayList.add(userInfo);
                }
            }
            return arrayList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private String m15571e(List<UserInfo> list) {
        String jSONArray;
        String str = C3657a.f18328f;
        try {
            JSONArray jSONArray2 = new JSONArray();
            for (UserInfo userInfo : list) {
                JSONObject jSONObject = new JSONObject();
                jSONObject.put("fuid", userInfo.uid);
                jSONArray2.put(jSONObject);
            }
            jSONArray = jSONArray2.toString();
        } catch (Exception e) {
            e.printStackTrace();
            jSONArray = str;
        }
        GuliLog.tracePrintInfo(TAG, "Sync Deleted UserInfos : " + jSONArray);
        return jSONArray;
    }

    public static boolean m15572e(UserInfo userInfo) {
        return userInfo.synced == 2;
    }

    public static boolean m15573f(UserInfo userInfo) {
        return userInfo.synced == -2;
    }

    public static boolean m15574g(UserInfo userInfo) {
        return userInfo.synced == 2 || userInfo.synced == -2;
    }

    // go generate a new uid
    private int m15575h() {
        UserInfo userInfo = (UserInfo) new Select().from(UserInfo.class).orderBy("UserId DESC").executeSingle();
        int i = userInfo != null ? userInfo.uid : 0;
        GuliLog.m12370d(TAG, "Lastest UserId : " + i);
        return i;
    }

    private void m15576h(UserInfo userInfo) {
        m15591b(userInfo, false);
    }

    private UserInfo m15577i() {
        PersonInfo readPersonInfoForScale = Keeper.readPersonInfoForScale();
        UserInfo userInfo = new UserInfo();
        userInfo.uid = -1;
        userInfo.height = readPersonInfoForScale.height;
        userInfo.weight = readPersonInfoForScale.weight;
        userInfo.targetWeight = readPersonInfoForScale.targetWeight;
        userInfo.birthday = readPersonInfoForScale.birthday;
        userInfo.gender = readPersonInfoForScale.gender;
        userInfo.name = readPersonInfoForScale.nickname;
        userInfo.avatarUrl = readPersonInfoForScale.avatarUrl;
        userInfo.synced = 1;
        return userInfo;
    }

    public UserInfo getInfoByUid(int i) { // m15578a
        UserInfo i2;
        if (i == -1) {
            i2 = m15577i();
        } else {
            i2 = (UserInfo) new Select().from(UserInfo.class).where("UserId=?", Integer.valueOf(i)).executeSingle();
        }
        GuliLog.tracePrintInfo(TAG, "Get Info : " + i + ", " + i2);
        return i2;
    }

    public UserInfo getInfoByName(String str) { // m15579a
        UserInfo userInfo = null;
        if (str != null) {
            userInfo = (UserInfo) new Select().from(UserInfo.class).where("Name=?", str).executeSingle();
        }
        GuliLog.tracePrintInfo(TAG, "Get Info : " + str + ", " + userInfo);
        return userInfo;
    }

    public List<UserInfo> m15580a(boolean z) {
        From a = new Select().from(UserInfo.class);
        if (!z) {
            Object[] objArr = new Object[]{Integer.valueOf(0)};
            a = a.where("Synced>?", Integer.valueOf(-1)).and("UserId!=?", objArr);
        }
        a.orderBy("UserId ASC");
        List<UserInfo> d = a.execute();
        GuliLog.tracePrintInfo(TAG, "Get All Infos : " + d.size());
        for (UserInfo userInfo : d) {
            GuliLog.tracePrintInfo(TAG, "Get Info : " + userInfo);
        }
        return d;
    }

    public boolean syncWithServer(Context context) { // m15581a
        List userList = getInfoNeedSync();
        GuliLog.m12370d(TAG, "Sync with Server 2, to server : " + userList.size());
        boolean z = true;
        if (!(userList == null || userList.isEmpty())) {
            z = true & syncUserInfosToServer(context, userList);
        }
        userList = m15602f();
        GuliLog.m12370d(TAG, "Sync with Server 3, delete from server : " + userList.size());
        return (userList == null || userList.isEmpty()) ? z : z & syncDeletedUserInfosToServer(context, userList);
    }

    class SyncUserInfoHandler extends AsyncHttpResponseHandler {
        final /* synthetic */ Context f11117a;
        final /* synthetic */ SyncResult f11118b;
        final /* synthetic */ boolean f11119c;
        final /* synthetic */ UserInfo f11120d;
        final /* synthetic */ UserInfoManager f11121e;

        SyncUserInfoHandler(UserInfoManager c1975j, Context context, SyncResult syncResult, boolean z, UserInfo userInfo) {
            this.f11121e = c1975j;
            this.f11117a = context;
            this.f11118b = syncResult;
            this.f11119c = z;
            this.f11120d = userInfo;
        }

        public void onFailure(int i, Header[] headerArr, byte[] bArr, Throwable th) {
            GuliLog.m12370d("UserInfoManager", "Sync UserInfo To Server Failure!!");
            if (bArr != null) {
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + new String(bArr));
            }
            this.f11118b.result = false;
        }

        public void onSuccess(int i, Header[] headerArr, byte[] bArr) {
            GuliLog.m12370d("UserInfoManager", "Sync UserInfo To Server Success!!");
            if (bArr != null) {
                String str = new String(bArr);
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + str);
                if (WebResponse.getWebResponse(this.f11117a, str).m11659c()) {
                    this.f11118b.result = true;
                    GuliLog.m12370d("UserInfoManager", "Result OK!!");
                    if (this.f11119c) {
                        String a = this.f11121e.m15567a(str, this.f11120d);
                        if (!TextUtils.isEmpty(a)) {
                            this.f11120d.avatarUrl = a;
                        }
                    }
                    this.f11120d.synced = 1;
                    this.f11121e.m15576h(this.f11120d);
                }
            }
        }
    }

    public boolean syncUserInfoToServer(Context context, UserInfo userInfo) { // m15582a
        boolean z = true;
        GuliLog.tracePrintInfo(TAG, "Sync UserInfo To Server!!");
        if (userInfo == null) {
            GuliLog.tracePrintInfo(TAG, "user == null");
            return true;
        } else if (userInfo.uid == 0) {
            GuliLog.tracePrintInfo(TAG, "user.uid == userinfo.useridunknown");
            return true;
        } else {
            SyncResult syncResult = new SyncResult();
            if (!TextUtils.isEmpty(userInfo.avatarUrl) || userInfo.avatarSource == null) {
                z = false;
            }
            WebAPI.syncUserInfoToServer(C0886a.m9071f(context), userInfo, z, new SyncUserInfoHandler(this, context, syncResult, z, userInfo));
            GuliLog.tracePrintInfo(TAG, "return result.result " + syncResult.result);
            return syncResult.result;
        }
    }

    // sync the user info from server
    class SyncUserInfoToLocalHandler extends AsyncHttpResponseHandler {
        final /* synthetic */ Context f11122a;
        final /* synthetic */ SyncResult f11123b;
        final /* synthetic */ aE f11124c;
        final /* synthetic */ UserInfoManager userinfoManager;

        SyncUserInfoToLocalHandler(UserInfoManager c1975j, Context context, SyncResult syncResult, aE aEVar) {
            this.userinfoManager = c1975j;
            this.f11122a = context;
            this.f11123b = syncResult;
            this.f11124c = aEVar;
        }

        public void onFailure(int i, Header[] headerArr, byte[] bArr, Throwable th) {
            GuliLog.m12370d("UserInfoManager", "Sync UserInfos To Local Failure!!");
            if (bArr != null) {
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + new String(bArr));
            }
            this.f11123b.result = false;
        }

        public void onSuccess(int i, Header[] headerArr, byte[] bArr) {
            GuliLog.m12370d("UserInfoManager", "Sync UserInfos To Local Success!!");
            if (bArr != null) {
                String str = new String(bArr);
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + str);
                WebResponse webResponse = WebResponse.getWebResponse(this.f11122a, str);
                if (webResponse.m11659c()) {
                    GuliLog.m12370d("UserInfoManager", "Result OK!!");
                    List<UserInfo> serverUserList = this.userinfoManager.getUserListFromWebResponse(str);
                    if (serverUserList != null) {
                        WeightGoalManager.getInstance().syncFromServer(this.f11122a, (List) serverUserList);
                        for (UserInfo userInfo : serverUserList) {
                            userInfo.synced = 1;
                        }
                        this.userinfoManager.mergeUserInfosFromServer((List) serverUserList);
                        if (this.userinfoManager.m15588a((List) serverUserList, false)) {
                            this.f11123b.result = true;
                            Keeper.keepScaleSyncedUserInfosFromServer(true);
                            if (this.f11124c != null) {
                                this.f11124c.onSuccess();
                            }
                        }
                    }
                } else if (webResponse.m11657a()) {
                    GuliLog.m12370d("UserInfoManager", "Result Empty OK!!");
                    this.f11123b.result = true;
                    Keeper.keepScaleSyncedUserInfosFromServer(true);
                    if (this.f11124c != null) {
                        this.f11124c.onSuccess();
                    }
                }
            }
        }
    }

    public boolean syncUserInfosToLocal(Context context, aE aEVar) { // m15583a
        GuliLog.tracePrintInfo(TAG, "Sync UserInfos To Local!!");
        SyncResult syncResult = new SyncResult();
        WebAPI.syncUserInfosToLocal(C0886a.m9071f(context), -1, true, new SyncUserInfoToLocalHandler(this, context, syncResult, aEVar));
        return syncResult.result;
    }

    public boolean syncUserInfosToServer(Context context, List<UserInfo> list) { // m15584a
        GuliLog.tracePrintInfo(TAG, "Sync UserInfos To Server!!");
        boolean z = true;
        for (UserInfo a : list) {
            z = !syncUserInfoToServer(context, a) ? false : z;
        }
        return z;
    }

    public boolean m15585a(UserInfo userInfo) {
        return addInfo(userInfo, true);
    }

    public boolean addInfo(UserInfo userInfo, boolean z) { // m15586a
        if (userInfo.uid == -1) {
            return false;
        }
        if (getInfoByName(userInfo.name) != null) {
            GuliLog.m12370d(TAG, "User Info : " + userInfo + ", name is already exist!!");
        }
        if (z) {
            userInfo.uid = m15575h() + 1;
        }
        userInfo.save();
        GuliLog.m12370d(TAG, "Add Info : " + userInfo);
        return true;
    }

    public boolean m15587a(List<UserInfo> list) {
        return m15588a((List) list, true);
    }


    public boolean m15588a(List<UserInfo> list, boolean flag) {
        GuliLog.m12370d("UserInfoManager", (new StringBuilder()).append("Add Infos : ").append(list.size()).toString());
        ActiveAndroid.beginTransaction();
        Iterator it = list.iterator();

        for (; it.hasNext(); addInfo((UserInfo) it.next(), flag)) { }

        // Misplaced declaration of an exception variable
        ActiveAndroid.setTransactionSuccessful();
        ActiveAndroid.endTransaction();
        return true;
    }

    public void deleteAllInfos() { // m15589b
        GuliLog.m12370d(TAG, "Delete All Infos!!");
        new Delete().from(UserInfo.class).execute();
    }

    public void deleteInfoMark(UserInfo userInfo) { // m15590b
        GuliLog.m12370d(TAG, "Delete Info Mark : " + userInfo);
        userInfo.synced = -1;
        m15576h(userInfo);
    }

    public void m15591b(UserInfo userInfo, boolean z) {
        GuliLog.m12370d(TAG, "Update Info : " + userInfo + ", markUpdated : " + z);
        if (userInfo.uid == -1) {
            PersonInfo readPersonInfo = Keeper.readPersonInfo();
            readPersonInfo.targetWeight = userInfo.targetWeight;
            if (z) {
                readPersonInfo.setNeedSyncServer(2);
            }
            Keeper.keepPersonInfo(readPersonInfo);
        } else if (userInfo.uid != 0) {
            if (z && userInfo.synced == 1) {
                userInfo.synced = 0;
            }
            userInfo.save();
        }
    }

    public void deleteInfosMark(List<UserInfo> list) { // m15592b
        GuliLog.m12370d(TAG, "Delete Infos Mark : " + list.size());
        ActiveAndroid.beginTransaction();
        try {
            for (UserInfo b : list) {
                deleteInfoMark(b);
            }
            ActiveAndroid.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ActiveAndroid.endTransaction();
        }
    }

    class C1979N implements aE {
        final /* synthetic */ aE f11130a;
        final /* synthetic */ UserInfoManager f11131b;

        C1979N(UserInfoManager c1975j, aE aEVar) {
            this.f11131b = c1975j;
            this.f11130a = aEVar;
        }

        public void onSuccess() {
            if (this.f11130a != null) {
                this.f11130a.onSuccess();
            }
        }

        public void onFailure() {
            if (this.f11130a != null) {
                this.f11130a.onFailure();
            }
        }
    }

    public boolean m15593b(Context context, aE aEVar) {
        boolean z = !Keeper.readScaleSyncedUserInfosFromServer();
        GuliLog.tracePrintInfo(TAG, "Sync with Server 1, from server : " + z);
        if (z) {
            return syncUserInfosToLocal(context, new C1979N(this, aEVar));
        }
        if (aEVar == null) {
            return true;
        }
        aEVar.onSuccess();
        return true;
    }

    class SyncDeletedUserInfosHandler extends AsyncHttpResponseHandler { // C1978M
        final /* synthetic */ Context f11126a;
        final /* synthetic */ SyncResult f11127b;
        final /* synthetic */ List f11128c;
        final /* synthetic */ UserInfoManager f11129d;

        SyncDeletedUserInfosHandler(UserInfoManager c1975j, Context context, SyncResult syncResult, List list) {
            this.f11129d = c1975j;
            this.f11126a = context;
            this.f11127b = syncResult;
            this.f11128c = list;
        }

        public void onFailure(int i, Header[] headerArr, byte[] bArr, Throwable th) {
            GuliLog.m12370d("UserInfoManager", "Sync Deleted UserInfos To Server Failure!!");
            if (bArr != null) {
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + new String(bArr));
            }
            this.f11127b.result = false;
        }

        public void onSuccess(int i, Header[] headerArr, byte[] bArr) {
            GuliLog.m12370d("UserInfoManager", "Sync Deleted UserInfos To Server Success!!");
            if (bArr != null) {
                String str = new String(bArr);
                GuliLog.tracePrintInfo("UserInfoManager", "Response : " + str);
                if (WebResponse.getWebResponse(this.f11126a, str).m11659c()) {
                    GuliLog.m12370d("UserInfoManager", "Result OK!!");
                    this.f11127b.result = true;
                    this.f11129d.deleteInfosLocal(this.f11128c);
                }
            }
        }
    }

    public boolean syncDeletedUserInfosToServer(Context context, List<UserInfo> list) { // m15594b
        GuliLog.tracePrintInfo(TAG, "Sync Deleted UserInfos To Server!!");
        if (list == null || list.isEmpty()) {
            return true;
        }
        SyncResult syncResult = new SyncResult();
        WebAPI.syncDeletedUserInfosToServer(C0886a.m9071f(context), m15571e((List) list), new SyncDeletedUserInfosHandler(this, context, syncResult, list));
        return syncResult.result;
    }

    public int m15595c() {
        int g = new Select().from(UserInfo.class).where("Synced>?", Integer.valueOf(-1)).count();
        GuliLog.tracePrintInfo(TAG, "Get All Infos Count : " + g);
        return g;
    }

    public void deleteInfoLocal(UserInfo userInfo) { // m15596c
        GuliLog.m12370d(TAG, "Delete Info Local : " + userInfo);
        userInfo.delete();
    }

    public void deleteInfosLocal(List<UserInfo> list) { // m15597c
        GuliLog.m12370d(TAG, "Delete Infos Local : " + list.size());
        ActiveAndroid.beginTransaction();
        try {
            for (UserInfo c : list) {
                deleteInfoLocal(c);
            }
            ActiveAndroid.setTransactionSuccessful(); //ActiveAndroid.m16251f();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ActiveAndroid.endTransaction();
        }
    }

    public List<UserInfo> m15598d() {
        List<UserInfo> e = m15601e();
        e.add(0, m15577i());
        GuliLog.tracePrintInfo(TAG, "Get All Infos With Self : " + e.size());
        return e;
    }

    public void m15599d(UserInfo userInfo) {
        m15591b(userInfo, true);
    }

    public void mergeUserInfosFromServer(List<UserInfo> list) { // m15600d
        GuliLog.tracePrintInfo(TAG, "Merge UserInfos From Server!!");
        List<UserInfo> localUserList = getInfoNeedSync();
        if (localUserList != null && localUserList.size() > 0 && list != null && list.size() > 0) {
            Collections.sort(list, new C1980O(this));
            int i = ((UserInfo) list.get(list.size() - 1)).uid;
            GuliLog.tracePrintInfo(TAG, "Lastest Server UserId : " + i);
            int i2 = i;
            for (UserInfo userInfo : localUserList) {
                int i3 = 0;
                int i4 = 0;
                int i5 = i2;
                for (UserInfo serverUserInfo : list) {
                    if (userInfo.name.equals(serverUserInfo.name)) {
                        GuliLog.tracePrintInfo(TAG, "With Same Name : " + userInfo.name);
                        serverUserInfo.height = userInfo.height;
                        serverUserInfo.weight = userInfo.weight;
                        serverUserInfo.birthday = userInfo.birthday;
                        serverUserInfo.gender = userInfo.gender;
                        serverUserInfo.targetWeight = userInfo.targetWeight;
                        if (userInfo.avatarSource != null) {
                            serverUserInfo.avatarSource = userInfo.avatarSource;
                            serverUserInfo.avatarUrl = null;
                        }
                        serverUserInfo.synced = 0;
                        i3 = serverUserInfo.uid;
                        i2 = 1;
                        int i6 = i3;
                        i3 = i5;
                        i5 = i6;
                    } else {
                        i5++;
                        i2 = i3;
                        i3 = i5;
                    }
                    i4 = i5;
                    i5 = i3;
                    i3 = i2;
                }
                WeightInfoManager a = WeightInfoManager.getInstance();
                List<WeightInfo> a2 = a.getInfosByUid(userInfo.uid);
                if (a2 != null && a2.size() > 0) {
                    for (WeightInfo weightInfo : a2) {
                        weightInfo.uid = i4;
                    }
                    a.updateInfos((List) a2);
                }
                if (i3 != 0) {
                    deleteInfoLocal(userInfo);
                } else {
                    userInfo.uid = i4;
                    m15576h(userInfo);
                }
                i2 = i5;
            }
        }
    }

    public List<UserInfo> m15601e() {
        return m15580a(false);
    }

    public List<UserInfo> m15602f() {
        List<UserInfo> d = new Select().from(UserInfo.class).where("Synced=?", Integer.valueOf(-1)).execute();
        GuliLog.tracePrintInfo(TAG, "Get Infos Deleted : " + d.size());
        for (UserInfo userInfo : d) {
            GuliLog.tracePrintInfo(TAG, "Deleted : " + userInfo);
        }
        return d;
    }

    public List<UserInfo> getInfoNeedSync() { // m15603g
        List<UserInfo> d = new Select().from(UserInfo.class).where("Synced=?", Integer.valueOf(0)).execute();
        GuliLog.tracePrintInfo(TAG, "Get Infos NeedSync : " + d.size());
        for (UserInfo userInfo : d) {
            GuliLog.tracePrintInfo(TAG, "NeedSync : " + userInfo);
        }
        return d;
    }
}
